import AddIcon from '@mui/icons-material/Add'
import { ButtonConfig } from '@/store/constant'
import { addGrade, updateGrade } from '@/api/index'
import { ButtonType, GradeItem } from '@/types/common'
import { GradeSelect } from '@/components'
import { SelectChangeEvent } from '@mui/material'
import { ChangeEvent } from 'react'
import { SET_SNACKBAR } from '@/store/actions'

type Props = {
  type: keyof ButtonType
  row: GradeItem
  refresh: () => void
  renderTrigger?: (props: any) => React.ReactNode
}

const defaultFormData = {
  id: 0,
  grade: '',
  credit_base: 0,
  credit_up: 0,
  performance_base: 0,
  performance_up: 0,
  next_grade: '',
  last_grade: ''
}
const handlerConfig = {
  add: addGrade,
  edit: updateGrade
}

// ---增、改---职级功能按钮
const GradeButton = ({ refresh, type = 'add', renderTrigger, row }: Props) => {
  const dispatch = useDispatch()
  const theme = useTheme()
  const fullScreen = useMediaQuery(theme.breakpoints.down('sm'))

  const { label } = ButtonConfig[type]
  const isAdd = type === 'add'
  const [open, setOpen] = useState(false)

  const { run, loading, error } = useRequest(get(handlerConfig, [type]), {
    manual: true,
    onSuccess() {
      refresh()
      dispatch({
        type: SET_SNACKBAR,
        payload: { children: `操作${error ? '失败: ' + error.message : '成功'}`, severity: error ? 'error' : 'success' }
      })
      setOpen(false)
      setFormData({ ...defaultFormData })
    }
  })

  const [formData, setFormData] = useState({ ...defaultFormData })
  const able = formData.grade && formData.next_grade && formData.last_grade

  const handleClose = () => {
    setOpen(false)
  }
  const handleOpen = () => {
    setOpen(true)
  }
  const handleChange = (key: string) => (e: SelectChangeEvent | ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => {
    const value = e.target.value
    if (['next_grade', 'last_grade'].includes(key)) {
      setFormData({ ...formData, [key]: value })
    }
    if (['credit_up', 'performance_up'].includes(key)) {
      if (!isNaN(Number(value))) {
        setFormData({ ...formData, [key]: Number(value) })
      }
    }
  }

  const handleConfirm = () => {
    const data = { ...formData }
    run(
      isAdd
        ? pick(data, ['grade', 'credit_up', 'performance_up', 'next_grade', 'last_grade'])
        : pick(data, ['id', 'credit_up', 'performance_up'])
    )
  }

  useEffect(() => {
    if (row) {
      setFormData({ ...row })
    }
  }, [row])

  return (
    <>
      {renderTrigger ? (
        renderTrigger({ onClick: handleOpen, disabled: type === 'delete' })
      ) : (
        <Button onClick={handleOpen} variant="outlined" size="small" color="secondary" startIcon={<AddIcon />}>
          {label}
        </Button>
      )}
      <Dialog fullWidth maxWidth="xs" fullScreen={fullScreen} open={open} onClose={handleClose}>
        <DialogTitle fontSize="1rem">{isAdd ? '新增' : '编辑'}</DialogTitle>
        <DialogContent>
          <Stack spacing={3} direction="column" padding={2}>
            <Divider>
              <Chip variant="outlined" color="secondary" label="当前职级" size="small" />
            </Divider>
            <GradeSelect value={formData.grade} onChange={handleChange('grade')} disabled={!isAdd} />
            <Divider>
              <Chip variant="outlined" color="secondary" label="Amount" size="small" />
            </Divider>
            <TextField
              required
              value={formData.credit_up}
              fullWidth
              margin="dense"
              autoFocus
              id="credit_up"
              name="credit_up"
              label="credit_up"
              type="text"
              onChange={handleChange('credit_up')}
            />
            <TextField
              required
              value={formData.performance_up}
              fullWidth
              margin="dense"
              autoFocus
              id="performance_up"
              name="performance_up"
              label="performance_up"
              type="text"
              onChange={handleChange('performance_up')}
            />
            <Divider>
              <Chip variant="outlined" color="secondary" label="职级调整" size="small" />
            </Divider>
            <GradeSelect
              value={formData.next_grade}
              onChange={handleChange('next_grade')}
              label="next_grade"
              disabled={!isAdd}
            />
            <GradeSelect
              value={formData.last_grade}
              onChange={handleChange('last_grade')}
              label="last_grade"
              disabled={!isAdd}
            />
          </Stack>
        </DialogContent>
        <DialogActions>
          <Button variant="outlined" onClick={handleClose}>
            Cancel
          </Button>
          <LoadingButton variant="contained" color="secondary" loading={loading} onClick={handleConfirm} disabled={!able}>
            应用
          </LoadingButton>
        </DialogActions>
      </Dialog>
    </>
  )
}

export default GradeButton
